package cn.com.nthotline.fragment;

import java.util.List;

import org.json.JSONArray;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import cn.com.nthotline.R;
import cn.com.nthotline.adapter.SubCategoryAdapter;
import cn.com.nthotline.constant.Constants;
import cn.com.nthotline.db.DBCategory;
import cn.com.nthotline.db.DatabaseFactory;
import cn.com.nthotline.fragment.ActionBarConfigurar.ActionBarConfigurarFactory;
import cn.com.nthotline.json.JsonPaserInterf;
import cn.com.nthotline.model.Category;
import cn.com.nthotline.util.CommonUtil;
import cn.com.nthotline.util.SharePreferenceUtil;
import cn.com.nthotline.widget.LoadingLayout;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

public class PubSubCatFragment extends Fragment implements
		ActionBarConfigurarFactory {

	private static final int SUCCESS = 1;
	private static final int DB_SUCCESS = 2;
	private static final int FAILED = 0;
	private static final int ERROR = -1;
	private Category category;
	private List<Category> list;
	private SubCategoryAdapter adapter;
	private AsyncHttpClient client = new AsyncHttpClient();
	private JsonPaserInterf jsonParser;
	private LoadingLayout load;
	private ListView listView;
	private DBCategory db;
	private String catId="";
	@Override
	public ActionBarConfigurar getActionBarConfigurar() {
		// TODO Auto-generated method stub
		return new ActionBarConfigurar() {

			@Override
			public String getTitle() {
				return category.getCatName();
			}

			@Override
			public boolean showCancelButton() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public String customTitle() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public boolean showBackButton() {
				return true;
			}

			@Override
			public String showRightButton() {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public boolean showRightSearch() {
				// TODO Auto-generated method stub
				return false;
			}

		};
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_common_listview,
				container, false);
		listView = (ListView) view.findViewById(R.id.listview);
		load = (LoadingLayout) view.findViewById(R.id.load);
		listView.setAdapter(adapter);
		registerListener();
		load.show();
		boolean hasdata = SharePreferenceUtil.getHasDataFlag(getActivity(),
				SharePreferenceUtil.HAS_SUB_CATEGORY+category.getCatId());
		if (hasdata) {
			loadFromDb();
		} else {
			loadCategory();
		}
		return view;
	}

	private void init() {
		category = (Category) getArguments().getSerializable("cat");
		catId=category.getCatId();
		adapter = new SubCategoryAdapter(getActivity());
		jsonParser = DatabaseFactory.getJsonPaserInterface();
		db = new DBCategory(getActivity());
	}

	private void registerListener() {
		listView.setOnItemClickListener(itemClick);
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Category cat=list.get(arg2);
			Bundle bundle=new Bundle();
			bundle.putSerializable("cat", cat);
			bundle.putString("id", category.getCatId());
			FragmentUtil.navigateTo(getFragmentManager(), new FragmentPublishedAdd(),bundle);
		}

	};
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			load.hide();
			adapter.clear();
			switch (msg.what) {
			case SUCCESS:
				SharePreferenceUtil.saveHasDataFlag(getActivity(),
						SharePreferenceUtil.HAS_SUB_CATEGORY+category.getCatId(), true);
				adapter.addAll(list);
				break;
			case DB_SUCCESS:
				adapter.addAll(list);
				break;
			case FAILED:
				CommonUtil.showShortToast(getActivity(), "");
				break;
			case ERROR:
				CommonUtil.showShortToast(getActivity(), (String) msg.obj);
				break;
			default:
				break;
			}
		}

	};

	private void loadFromDb() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				list = db.queryCategoryById(category.getCatId());
				if (list != null && list.size() > 0) {
					handler.sendEmptyMessage(DB_SUCCESS);
				} else {
					handler.sendEmptyMessage(FAILED);
				}
			}
		}).start();
	}

	private void loadCategory() {
		client.get(getActivity(), Constants.CATEGORY + category.getCatId(),
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(JSONArray array) {
						// TODO Auto-generated method stub

						try {
							list = jsonParser.parserCategoryData(array);
							if (list != null && list.size() > 0) {
								for (Category t : list) {
									db.insert(t);
								}
								handler.sendEmptyMessage(SUCCESS);
							} else {
								handler.sendEmptyMessage(FAILED);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							handler.sendEmptyMessage(FAILED);
						}
					}

					@Override
					public void onFailure(Throwable arg0, String arg1) {
						// TODO Auto-generated method stub
						CommonUtil.sendMessage(handler, ERROR, arg1);
					}
				});
	}

}
